import Vue from 'vue'
import Vuex from 'vuex'

import { loginAPI } from '@/api/login.js'
import { getStorage, setStorage } from '@/utils/storage.js'
import { userInfoAPI } from '@/api/user'

Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    token: getStorage('token') || '',
    refresh_token: getStorage('refresh_token') || '',
    user: JSON.parse(getStorage('user')) || {} // 用户基本资料(默认从本地取)
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setStorage('token', token)
    },
    setRefreshToken(state, refreshToken) {
      state.refresh_token = refreshToken
      setStorage('refresh_token', refreshToken)
    },
    setUser(state, userObj) {
      state.user = userObj
      setStorage('user', JSON.stringify(userObj))
    },
    updatePhoto(state, photo) {
      state.user.photo = photo
      setStorage('user', JSON.stringify(state.user))
    },
    updateName(state, theName) {
      state.user.name = theName
      setStorage('user', JSON.stringify(state.user))
    }
  },

  actions: {
    async asyncLoginAction(store, val) {
      try {
        const res = await loginAPI(val)
        const { token, refresh_token } = res.data.data
        store.commit('setToken', token)
        store.commit('setRefreshToken', refresh_token)
        return Promise.resolve(res) // 返回成功的Promise对象
      } catch (err) {
        return Promise.reject(err) // 返回失败的Promise对象
      }
    },
    // 用户没有加载我的页面直接跳转到小思上时，就要用到这步保险，把获取用户信息的接口重新调用再传递给mutation中
    async getuserinfo(store) {
      const res = await userInfoAPI()
      store.commit('setUser', res.data.data)
    }
  },
  getters: {
    userPhoto(state) {
      if (state.user.photo === undefined) {
        store.dispatch('getUserInfo')
      }
      return state.user.photo
    }
  }
})
export default store
